<?php

namespace App\Repositories;

use App\Models\TestingResultType;
use App\Models\TestingResultAttribute;
use App\Services\CommonHelper;
use App\Services\Result\CustomerQuestionnaireTestingResult;
use App\Services\Result\RecipeTestingResult;
use Cache;
use UserRecordService;
use TestingDetailService;
use App\Services\Result\DecreaseWeightResult;
use App\Services\Result\OilResult;
use App\Services\Result\TraditionalMedicineResult;
use App\Services\Result\WestMedicineResult;
use App\Services\Result\FourteenDecWeightResult;
use App\Services\Result\DWeightNoqrCodeResult;
use App\Services\Result\ZAhealthResult;
use App\Services\Result\ZAhealthVtwoResult;
use App\Services\Result\FigureResult;
use App\Services\Result\PostpartumDepressionResult;
use App\Services\Result\SomnolenceDuringPregnancyTestingResult;
use App\Services\Result\BoneHealthDuringPregnancyTestingResult;
use App\Services\Result\PostpartumWeightRetentionTestingResult;
use App\Services\Result\ChildhoodAutismResult;
use App\Services\Result\MentalHealthResult;
use App\Services\Result\ChineseMedicineConstitutionTestingHlsResult;
use App\Services\Result\PressureTestingResult;
use App\Services\Result\JointDexterityTestingResult;
use App\Services\Result\InfantBehavioralNerveTestingResult;
use App\Services\Result\AndropauseTestingResult;
use App\Services\Result\QuestionnaireTestingResult;
use App\Services\Result\QuestionnaireSpecialTestingResult;
use App\Services\Result\ZYhealthResult;
use App\Services\Result\SleepingTestingNewResult;
use App\Services\Result\ExerciseLevelTestingResult;
use App\Services\Result\ZADietResult;
use App\Services\Result\ZAPressureResult;
use App\Services\Result\ZAMentalResult;
use App\Services\Result\ElbooTestingResult;
use App\Services\Result\ElbooSevenTestingResult;
use App\Services\Result\GSTestingResult;
use App\Services\Result\sevenTestingResult;
use App\Services\Result\currencyTestingResult;
use App\Services\Result\MetaWeightResult;
use App\Services\Result\MetaWeightOptResult;
use TestingConfig;
use App\Models\LogHelper;
use App\Services\Result\EnterpriceHealthTestingResult;

class TestingResultTypeRepository extends Repository
{
    static $tag = 'testing.result.type';


    /**根据题目结果id和分数查询测评结果数据
     * @param $id_arr 题目关联的结果id数组
     * @param $score 测评分数.php artisan cache:clear
     * @return array 查询结果
     */
    public function getResult($uid, $id_arr, $score, $tid = null)
    {

        $key = getCacheKey('testing.result.type.result.info');
        $key = $key . $score . $uid . $tid;
        $list = $this->remember($key, function () use ($id_arr, $score) {
            $result = TestingResultType::whereIn('id', $id_arr)
                ->where('max_score', '>=', $score)
                ->where('min_score', '<=', $score)
                ->select('attr_ids')
                ->firstOrFail();
            $attrs = explode(',', $result['attr_ids']);
            return TestingResultAttribute::whereIn('id', $attrs)
                ->select('id as attr_id', 'title', 'note')
                ->orderBy('attr_id', 'desc')
                ->get();
        });
        /*  dd($list);*/
        return $list;
    }


    /**返回额外字符串
     * @param $tid
     * @param $arr
     * @param $score
     * @return mixed
     */
    public function result($tid, $arr, $score)
    {
        $cacheKey = getCacheKey('testing.sjb.cache_key.testing.result.type');
        $cacheKey = $cacheKey . $tid . $score;
        $cate = $this->remember($cacheKey, function () use ($arr, $score) {
            return TestingResultType::select('title', 'factor_str')
                ->whereIn('id', $arr)
                ->where('max_score', '>', $score)
                ->where('min_score', '<=', $score)
                ->first()->toarray();
        });
        return $cate;
    }

    /**返回用于拼装测评结论的title
     * @param $id_arr
     * @param $score
     * @return mixed
     */
    public function getTitle($id_arr, $score)
    {

        LogHelper::log('get title socre is===============>' . $score, 'zhongan');
        $title = "";
        if (!is_null($score)) {
            $result = TestingResultType::whereIn('id', $id_arr)
                ->where('min_score', '<=', $score)
                ->where('max_score', '>=', $score)
                ->select('title')
                ->firstOrFail();
            $title = $result['title'] ? $result['title'] : "";
        }
        return $title;
    }

    public function getById($id)
    {
        $cacheKey = getCacheKey('testing.cache_key.result_type.info') . $id;
        $value = $this->remember($cacheKey, function () use ($id) {
            return TestingResultType::where('id', $id)
                ->first();
        });
        return $value;
    }

    public function getResultOptions()
    {
        $list = TestingResultType::all();
        $data = [];
        if ($list) {
            $obj = array();
            foreach ($list as $key => $val) {
                $obj['id'] = $val['id'];
                $obj['text'] = $val['title'];
                array_push($data, $obj);
            }
        }
        return $data;
    }


    public function chooseResult($uid, $detail_id)
    {
        LogHelper::log('enter chooseResult, uid=' . $uid . ' tid=' . $detail_id, 'zhongan');
        $data = [];
        $result = UserRecordService::getByUid($uid, $detail_id);
        $freeOrderId = isset($result['free_order_id']) ? $result['free_order_id'] : 0 ;
        if ($result) {
            $data = $this->getAttribute($uid, $detail_id, $result['score'], $result['final_answers'],$freeOrderId);
            return $data;
        } else {
            return apiError();
        }

    }

    /**
     * 根据用户的答题记录获取答题建议
     * @param $recordId 记录编号
     */
    public function getUserAttributeByRecordId($recordId)
    {
        $redisKey = getCacheKey('testing.user_record.attributes');
        $attributes = $this->remember($redisKey, function () use ($recordId) {
            $record = UserRecordService::getById($recordId);
            $uid = $record['uid'];
            $tid = $record['tid'];
            $score = $record['score'];
            $finalAnswerStr = $record['final_answers'];
            $freeOrderId = isset($record['free_order_id']) ? $record['free_order_id'] : 0 ;
            $anylasisResult = $this->getAttribute($uid, $tid, $score, $finalAnswerStr,$freeOrderId);
            //获取答案的建议
            $attributes = $anylasisResult['attrs'];
            //获取答案
//            $answers = $this->getUserAnswerByRecord($record);
//            $data['answers'] = $answers;
            $data['attributes'] = $attributes;
            return $data;
        });
        return $attributes;
    }


    /**
     * 根据用户答题记录获取用户的答案
     */
    public function getUserAnswerByRecord($userRecord)
    {
        $tid = $userRecord['tid'];
        $testingDetail = TestingDetailService::getItem($tid);
        $items = $testingDetail['questionList'];
        $answerStr = $userRecord['answers'];
        $answers = CommonHelper::convertAnswerToObj($answerStr);
        $indexes = array_keys($answers);
        $list = [];
        foreach ($items as $item) {
            $index = $item['index'];
            if (in_array($index, $indexes)) {
                $obj['index'] = $index;
                $obj['question'] = $item['title'];
                $obj['answer'] = $answers[$index]['answer'];
                array_push($list, $obj);
            }
        }
    }


    protected function getAttribute($uid, $tid, $score, $finalAnswerStr,$freeOrderId)
    {
        LogHelper::log('enter getAttribute, uid=' . $uid . ' tid=' . $tid . ' answer=' . $finalAnswerStr, 'zhongan');
        $detail = TestingDetailService::getById($tid);
        if ($detail) {
            $resultTypeIdArr = explode(',', $detail['result_type']);
            $result = $this->chooseAttributeRoute($tid, $uid, $score, $resultTypeIdArr, $finalAnswerStr,$freeOrderId);
            return $result;
        } else {
            return apiError();
        }
    }

    protected function chooseAttributeRoute($tid, $uid, $score, $resultTypeIdArr, $finalAnswerStr,$freeOrderId)
    {
        $testingDetail = TestingDetailService::getById($tid);
        //这部分为通过减脂后台自动创建问卷的逻辑算法部分
        if (isset($testingDetail['create_by']) && $testingDetail['create_by'] == TestingDetailRepository::CREATE_BY_JZ_CUSTOMER) {
            $instance = new CustomerQuestionnaireTestingResult($finalAnswerStr);
            $result = $instance->result();
        } else {
            LogHelper::log('enter chooseAttributeRoute, uid=' . $uid . ' tid=' . $tid, 'zhongan');
            $data = [];
            //14天減重計劃
            $fourteendw = intval(TestingConfig::getValue('TW.fat.testing.id', 19));
            $tbTradionTid = intval(TestingConfig::getValue('TB.testing.tradition.id', 22));
            $tbWestTid = intval(TestingConfig::getValue('TB.testing.west.id', 23));
            $oilTestTid = intval(TestingConfig::getValue('Oil.testing.id', 25));
            $recipeTestingTid = intval(TestingConfig::getValue('RT.testing.id', 24));
            //21天无二维码
            $dwnoqrcode = intval(TestingConfig::getValue('DW.noqrcode.fat.testing.id', 18));
            //众安健康测评
            $zaHealthId = intval(TestingConfig::getValue('ZA.health.id', 33));
            //众安健康测评2.0
            $zaHealthIdVtwo = intval(TestingConfig::getValue('ZA.V2.health.id', 43));
            //增加结果缓存
            $cacheKey = getCacheKey('testing.cache_key.user_recode.record') . $tid . "_" . $uid;
            $figureTestingTid = intval(TestingConfig::getValue('Figure.testing.id', 31));
            $postpartumDepressionTestingTid = intval(TestingConfig::getValue('PostpartumDepression.testing.id', 32));
            $SomnolenceDuringPregnancyTestingTid = intval(TestingConfig::getValue('SomnolenceDuringPregnancy.testing.id', 34));
            $BoneHealthDuringPregnancyTestingTid = intval(TestingConfig::getValue('bone.health.during.pregnancy.testing.id', 35));
            $PostpartumWeightRetentionTestingTid = intval(TestingConfig::getValue('postpartum.weight.retention.testing.id', 36));
            $ChildhoodAutismTestingTid = intval(TestingConfig::getValue('childhood.autism.testing.id', 37));
            $MentalHealthTestingTid = intval(TestingConfig::getValue('mental_health_testing.id', 39));
            $PressureTestingTid = intval(TestingConfig::getValue('pressure.testing.id', 38));
            $JointDexterityTestingTid = intval(TestingConfig::getValue('joint.dexterity.testing.id', 40));
            $InfantBehavioralNerveTestingTid = intval(TestingConfig::getValue('infant_behavioral_nerve_testing.id', 41));
            $ChineseMedicineConstitutionTestingHlsTid = intval(TestingConfig::getValue('chinese_medicine_constitution_testing_hls.id', 42));
            $AndropauseTestingTid = intval(TestingConfig::getValue('andropause_testing.id', 47));
            //s14轻体测第一周问卷
            $questionnaireTid = intval(TestingConfig::getValue('s14_questionnaire.id', 53));
            //s14轻体测结束问卷
            $questionnaireOverTid = intval(TestingConfig::getValue('s14_over_questionnaire.id', 54));
            //s21轻体测第一周问卷
            $questionnaireOneTid = intval(TestingConfig::getValue('s21_one_questionnaire.id', 55));
            //s21轻体测第二周问卷
            $questionnaireTwoTid = intval(TestingConfig::getValue('s21_two_questionnaire.id', 56));
            //s21轻体测结束问卷
            $questionnaireOversTid = intval(TestingConfig::getValue('s21_over_questionnaire.id', 57));
            $ZyReplaceTestingTid = intval(TestingConfig::getValue('zy_replace_testing.id', 58));
            //JHR健康问卷
            $jhrTid = intval(TestingConfig::getValue('jhr_testing.id', 59));
            //YC轻体调查问卷
            $ycTid = intval(TestingConfig::getValue('yc_testing.id', 60));
            $SleepingTestingNewTid = intval(TestingConfig::getValue('sleeping_testing_new.id', 65));
            $ExerciseLevelTestingTid = intval(TestingConfig::getValue('exercise_level_testing.id', 66));
            //减脂后台引流测评
            $flowTid = intval(TestingConfig::getValue('flow_testing.id', 67));
            //减脂后台引流测评（hw测评）
            $flowJhrTid = intval(TestingConfig::getValue('jhr_testing_special.id', 68));
            //益步14天轻体测评
            $elbooTid = intval(TestingConfig::getValue('elboo.testing.id', 73));
            //益步7天轻体测评
            $elbooSevenTid = intval(TestingConfig::getValue('elboo.seven.testing.id', 74));
            //益步7天问卷
            $questionnaireS7Tid = intval(TestingConfig::getValue('s7_questionnaire.id', 82));
            //茄子7天测评
            $sevenTid = intval(TestingConfig::getValue('qiezi.s7.testing.id', 74));
            //茄子健康通用轻体测评
            $currencyTid =  intval(TestingConfig::getValue('qiezi.currency.testing.id',84));
            //代谢用户测评
            $metaTid = intval(TestingConfig::getValue('jz.meta.testing.id',86));
            //s3结束问卷
            $thereQuestionnaireTid = intval(TestingConfig::getValue('s3_over_questionnaire.id',87));
            //代谢用户测评(题目优化版)
            $metaOptTid = intval(TestingConfig::getValue('jz.meta.testing.opt.id',90));

            $zaDietTid = intval(TestingConfig::getValue('za.diet.testing.id', 69));
            $zaPressureTid = intval(TestingConfig::getValue('za.pressure.testing.id', 70));
            $zaMentalTid = intval(TestingConfig::getValue('za.mental.testing.id', 71));
            $enterpriceHealthTid = intval(TestingConfig::getValue('enterprice.health.testing.id', 79));
            $gsTid = intval(TestingConfig::getValue('gs.testing.id', 78));

            switch ($tid) {
                case 21 :
                    $instance = new DecreaseWeightResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $tbTradionTid:
                    $instance = new TraditionalMedicineResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $tbWestTid:
                    $instance = new WestMedicineResult($finalAnswerStr, $score);
                    $result = $instance->result();
                    break;
                case $oilTestTid:
                    $instance = new OilResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $recipeTestingTid:
                    $instance = new RecipeTestingResult($uid, $tid, $finalAnswerStr, $score);
                    $result = $instance->result();
                    break;
                case $fourteendw :
                    $instance = new FourteenDecWeightResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $dwnoqrcode:
                    $instance = new DWeightNoqrCodeResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $zaHealthId:
                    $result = UserRecordService::remember($cacheKey, function () use ($finalAnswerStr) {
                        $instance = new ZAhealthResult($finalAnswerStr);
                        $resultData = $instance->result();
                        return $resultData;
                    });
                    break;
                case $zaHealthIdVtwo:
                    $instance = new ZAhealthVtwoResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $figureTestingTid:
                    $instance = new FigureResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $postpartumDepressionTestingTid:
                    $instance = new PostpartumDepressionResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $SomnolenceDuringPregnancyTestingTid:
                    $instance = new SomnolenceDuringPregnancyTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $BoneHealthDuringPregnancyTestingTid:
                    $instance = new BoneHealthDuringPregnancyTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $PostpartumWeightRetentionTestingTid:
                    $instance = new PostpartumWeightRetentionTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $ChildhoodAutismTestingTid:
                    $instance = new ChildhoodAutismResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $MentalHealthTestingTid:
                    $instance = new MentalHealthResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $PressureTestingTid:
                    $instance = new PressureTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $JointDexterityTestingTid:
                    $instance = new JointDexterityTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $InfantBehavioralNerveTestingTid:
                    $instance = new InfantBehavioralNerveTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $ChineseMedicineConstitutionTestingHlsTid:
                    $instance = new ChineseMedicineConstitutionTestingHlsResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $AndropauseTestingTid:
                    $instance = new AndropauseTestingResult($tid, $uid, $score, $resultTypeIdArr, $finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $questionnaireTid:
                    $instance = new QuestionnaireSpecialTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $questionnaireOverTid:
                    $instance = new QuestionnaireSpecialTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $questionnaireOneTid:
                    $instance = new QuestionnaireTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $questionnaireTwoTid:
                    $instance = new QuestionnaireTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $questionnaireOversTid:
                    $instance = new QuestionnaireTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $ZyReplaceTestingTid:
                    $instance = new ZYhealthResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $jhrTid:
                    $instance = new QuestionnaireTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $ycTid:
                    $instance = new QuestionnaireTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $flowTid:
                    $instance = new DecreaseWeightResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $flowJhrTid:
                    $instance = new QuestionnaireTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $SleepingTestingNewTid:
                    $instance = new SleepingTestingNewResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $ExerciseLevelTestingTid:
                    $instance = new ExerciseLevelTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $zaDietTid:
                    $instance = new ZADietResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $zaPressureTid:
                    $instance = new ZAPressureResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $zaMentalTid:
                    $instance = new ZAMentalResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $elbooTid:
                    $instance = new ElbooTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $elbooSevenTid:
                    $instance = new ElbooSevenTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $enterpriceHealthTid:
                    $instance = new EnterpriceHealthTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $gsTid:
                    $instance = new GSTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $questionnaireS7Tid:
                    $instance = new QuestionnaireSpecialTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $sevenTid:
                    $instance = new sevenTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $currencyTid:
                    $instance = new currencyTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                case $metaTid :
                    $instance = new MetaWeightResult($finalAnswerStr,$freeOrderId,$uid,$tid);
                    $result = $instance->result();
                    break;
                case $metaOptTid :
                    $instance = new MetaWeightOptResult($finalAnswerStr,$freeOrderId,$uid,$tid);
                    $result = $instance->result();
                    break;
                case $thereQuestionnaireTid:
                    $instance = new QuestionnaireSpecialTestingResult($finalAnswerStr);
                    $result = $instance->result();
                    break;
                default :
                    $r = $this->getResult($uid, $resultTypeIdArr, $score, $tid);
                    $r = str_replace('{{SCORE}}', $score, $r);
                    $r = json_decode($r);
                    $result['attrs'] = $r;
                    $result['chatparam'] = '';
                    $result['chatType'] = '';
                    break;
            }
        }
        $data['attrs'] = $result['attrs'] ? $result['attrs'] : '';
        $data['chatparam'] = $result['chatparam'] ? $result['chatparam'] : '';
        $data['chatType'] = $result['chatType'] ? $result['chatType'] : '';
        return $data;
    }


    public function cacheTime()
    {
        return config('testing.common_cache_time');
    }


    public function model()
    {
        return app(TestingResultType::class);
    }

    public function tag()
    {
        return self::$tag;
    }
}
